<template>
  <!-- 页头 -->
  <header class="header">
    <div class="logoTitle">
      <router-link to="/index">
        <!-- <img src="@/assets/logo/logo.png" alt="" class="img">
        <span class="title">{{ sysTitle }}</span> -->
        <img src="@/assets/images/home/title.png" :alt="sysTitle" :title="sysTitle" class="img">
      </router-link>
      <el-link v-if="objDataManager.menuRouter" :href="objDataManager.menuRouter || '/'" class="data-manager"
        :underline="false" target="_blank" @click="saveLogs(objDataManager)">
        <img src="@/assets/images/home/data-manager.png" alt="数据管理" title="数据管理" class="img-data-manager">
      </el-link>
      <el-link v-if="objCensus.menuRouter" :href="setSystemHref(objCensus)" class="data-manager" :underline="false"
        target="_blank" @click="saveLogs(objCensus)" style="margin-left: 20px;">
        <img src="@/assets/images/home/bg-system.png" title="全国灾害综合风险普查业务系统（地震）" />
        <div class="data-manager-text">风险普查</div>
      </el-link>
    </div>
    <div class="right-menu">
      <template v-if="appStore.device !== 'mobile'">
        <span>
          <el-dropdown ref="dropdown" :hide-on-click="false" @command="handleDropdown">
            <span class="dropdown-user">
              <img src="@/assets/images/home/icon-user.png">{{ userStore.name }}
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </span>
        <span class="icon-message" @click="dialogVisible = true">
          <el-badge is-dot :hidden="arrMessage.length ? false : true"><img
              src="@/assets/images/home/icon-message.png"></el-badge>消息
        </span>
        <span @click="logout">
          <img src="@/assets/images/home/icon-logout.png">退出
        </span>
        <span v-if="arrResourcesMenus" class="el-dropdown-link icon-link">
          <el-dropdown @command="handleCommand" popper-class="dropdown-link" trigger="hover" :teleported="false">
            <img src="@/assets/images/home/icon-link.png">
            <template #dropdown>
              <el-dropdown-menu>
                <router-link to="/iconModle/imgTemplateManage">
                  <el-dropdown-item command="imgTemplateManage">图件模板库</el-dropdown-item>
                </router-link>
                <router-link to="/iconModle/figureSymbolManage">
                  <el-dropdown-item command="figureSymbolManage">图形符号库</el-dropdown-item>
                </router-link>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </span>
      </template>
    </div>
    <div class="avatar-container">
      <el-dropdown @command="handleCommand" class="right-menu-item hover-effect" trigger="click" :teleported="false">
        <el-icon :size="24" color="rgb(0 255 228)" style="vertical-align: middle">
          <Menu />
        </el-icon>
        <template #dropdown>
          <el-dropdown-menu>
            <template v-if="arrResourcesMenus">
              <router-link to="/iconModle/imgTemplateManage">
                <el-dropdown-item command="imgTemplateManage">图件模板库</el-dropdown-item>
              </router-link>
              <router-link to="/iconModle/figureSymbolManage">
                <el-dropdown-item command="figureSymbolManage">图形符号库</el-dropdown-item>
              </router-link>
            </template>
            <el-dropdown-item divided command="logout">
              <span>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </header>
  <!-- 修改密码 -->
  <UpdatePassword v-if="visiblePwd" v-model:show="visiblePwd" />
  <!-- 消息弹框 -->
  <Message v-if="dialogVisible" :list="arrMessage" @close="(val) => dialogVisible = val || false"></Message>
</template>

<script setup>
// 修改密码
import UpdatePassword from "@/components/Home/Header/UpdatePwd";
// 消息弹框
import Message from "@/components/Home/Message";
import { ElMessageBox } from 'element-plus';
// 获取消息列表
import { getMessageApi } from '@/api/user';
// 引入添加日志接口
import { addLogsApi } from '@/api/iconModle/logManage.js';
// 公用方法
import { parseTime } from "@/utils/ruoyi.js";
// 引入store
import usePermissionStore from '@/store/modules/permission';
import useUserStore from '@/store/modules/user';
import useAppStore from "@/store/modules/app";
import { ref, watch } from "vue";
// 获取pinia
const permissionStore = usePermissionStore();
const userStore = useUserStore();
const appStore = useAppStore();

// 获取当前实例
const { proxy } = getCurrentInstance();
// 用户id
const userId = computed(() => useUserStore().userId);

// 数据管理路径
let objDataManager = ref({});
// 人口普查路径
let objCensus = ref({});
// 资源管理菜单
let arrResourcesMenus = ref(null);
// 菜单列表
const arrMenus = computed(() => permissionStore.menus || '');
// 执行并追踪依赖，依赖更改时重新执行
watchEffect(() => {
  if (arrMenus.value && arrMenus.value.length) {
    arrMenus.value.map((item) => {
      // 数据管理, 同时控制权限，有则显示数据管理部分
      if (item.name == '/mhsjgl') {
        objDataManager.value = item;
      } else if (item.name == '/iconModle') {
        arrResourcesMenus.value = item;
      } else if (item.name == '/rkpc' && userStore.showRkpc) {
        objCensus.value = item;
      }
    })
  }
})

// 系统名称
const sysTitle = ref(import.meta.env.VITE_APP_TITLE);

// 显示修改密码弹框
let visiblePwd = ref(false);
// 用户，下拉列表切换
function handleDropdown(command) {
  switch (command) {
    case "updatePassword":
      visiblePwd.value = true;
      break;
    default:
      break;
  }
}
// 下拉列表切换
function handleCommand(command) {
  switch (command) {
    case "logout":
      logout();
      break;
    case "imgTemplateManage":
    case "figureSymbolManage":
      if (arrResourcesMenus.value && arrResourcesMenus.value.children && arrResourcesMenus.value.children.length) {
        arrResourcesMenus.value.children.some(item => {
          if (item.menuRouter && item.menuRouter.indexOf(command) > -1) {
            saveLogs(item);
            return true;
          }
        })
      }
      break;
    default:
      break;
  }
}

// 添加日志
function saveLogs(logs) {
  addLogsApi({
    funcId: logs.name, // 功能名称
    relObjType: 'Open subsystem',
    logMemo: logs.meta.title, // 说明
    serverName: logs.menuRouter, // 服务名称
    logData: parseTime(new Date()), // 时间
  }).then(res => {
    const { code, data, message } = res;
    if (code == 200) {
      console.log('添加日志成功！跳转：' + logs.menuRouter)
    }
  }).catch(err => {
    console.error(err.message || '添加日志失败！')
  })
}

// 退出
function logout() {
  console.log(this)
  ElMessageBox.confirm('请确定是否退出当前用户登录？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logOut().then(res => {
      const { code, retUrl } = res;
      if (code == 200 && retUrl) {
        const tIndex = retUrl.indexOf('?toUrl=');
        if (tIndex > -1) {
          // 去掉cssSsoTicket
          const strHref = location.href.replace(/\?cssSsoTicket=.*/gi, '');
          location.href = retUrl.slice(0, tIndex + 7) + strHref;
        } else {
          location.href = retUrl;
        }
      } else {
        proxy.$modal.msgWarning('退出登录失败！');
      }
    })
  }).catch(() => { });
}

// 显示消息弹框
let dialogVisible = ref(false);
// 消息列表
let arrMessage = ref([]);
// 获取消息列表
function getMessage() {
  getMessageApi().then(res => {
    const { code, data, message } = res;
    if (code == 200) {
      arrMessage.value = data || [];
    }
  }).catch(err => {
    console.log(err.message || '获取消息失败！');
  })
}

// 设置系统访问路径
function setSystemHref(item) {
  // 默认不可点击
  let strHref = 'javascript:void(0)';
  // 判断是否有配置访问地址，人口普查系统，特殊处理，传参对接单点
  if (item.menuRouter && (item.meta?.title?.indexOf('人口普查') != -1 || item.funcode == 'rkpc')) { // 用功能编码判断，路径要用作加载图片
    strHref = item.menuRouter + '?platformToken=' + (userId.value || '')
  }
  return strHref;
}

// 组件已挂载
onMounted(() => {
  // 获取消息列表
  getMessage();
})
</script>

<style lang="scss">
.dropdown-link.el-dropdown__popper.el-popper {
  background: transparent;
  width: 120px;
  border: none;
  overflow: hidden;

  >.el-popper__arrow {
    display: none;
  }

  .el-dropdown-menu {
    background-color: #005cbc80;
    padding: 0;

    .el-dropdown-menu__item {
      line-height: 30px;
      color: var(--el-color-white);
    }

    .el-dropdown-menu__item:hover {
      background-color: #005cbccc;
    }
  }
}
</style>
<style lang='scss' scoped>
.header {
  height: 80px;
  padding: 0 80px;
  display: flex;
  align-items: center;
  overflow: hidden;
  justify-content: space-between;
  color: #ffffff;

  .logoTitle {
    display: flex;
    align-items: center;

    .img {
      height: 80px;
    }

    .title {
      margin-left: 15px;
      color: #ffffff;
      font-size: 24px;
      font-weight: 700;
    }

    .data-manager {

      .img-data-manager {
        margin-left: 60px;
      }

      .data-manager-text {
        position: absolute;
        top: 0;
        width: 100%;
        line-height: 50px;
        text-align: center;
        font-size: 24px;
        color: #04ffff;
      }
    }
  }

  .right-menu {
    min-width: 365px;
    text-align: right;

    >span {
      margin-left: 20px;
      cursor: pointer;
      vertical-align: middle;
      line-height: 32px;

      img {
        margin-bottom: -5px;
        margin-right: 10px;
      }
    }

    /* 消息 */
    span.icon-message {

      /* 徽章 */
      .el-badge {

        :deep(sup.is-fixed) {
          right: 18px;
          top: 5px;
          border: none;
          width: 10px;
          height: 10px;
          background-color: red;
        }
      }
    }

    .el-dropdown-link {
      cursor: pointer;
      color: var(--el-color-primary);
      align-items: center;
      position: relative;
      top: 5px;

      img {
        margin-right: 0;
      }
    }
  }
}

.dropdown-user {
  color: #ffffff;
}

.avatar-container {
  display: none;

  .avatar-wrapper {
    margin-top: 5px;
    position: relative;

    .user-avatar {
      cursor: pointer;
      width: 40px;
      height: 40px;
      border-radius: 10px;
    }

    i {
      cursor: pointer;
      position: absolute;
      right: -20px;
      top: 25px;
      font-size: 12px;
    }
  }
}

/******************** 响应式布局 **********************/
@media screen and (max-device-width: 1080px) {
  .header {
    height: auto;
    padding: 0 15px;

    .logoTitle {
      width: 100%;
      flex-wrap: wrap;

      .img {
        height: 36px;
      }

      .data-manager {
        display: block;
        margin-top: 30px;
        width: 100%;
        text-align: center;

        .img-data-manager {
          margin: 0;
        }
      }
    }

    .right-menu {
      display: none;
    }

    .avatar-container {
      display: block;
      position: absolute;
      top: 35px;
      right: 15px;
    }
  }
}
</style>